import EventEmitter from "events";
import * as vscode from "vscode";
import { EnginesTitle, EnumEngine } from "./engine";
import { cache } from "./helper";
import { mirServer, MirServerProvider } from "./extension";

type EngineType = { name: EnumEngine; title: string };

type EventMap = {
  change: [engine: EngineType];
};
export class EngineProvider extends EventEmitter<EventMap> implements MirServerProvider {
  statusBar: vscode.StatusBarItem;
  name: EnumEngine = EnumEngine.E_LF;
  private _active: boolean = false;
  constructor() {
    super();
    this.statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 0);
    this.statusBar.text = EnginesTitle[this.name];
    this.statusBar.tooltip = "点击选择引擎";
    this.statusBar.command = "mirServer.statusBar.SelectEngine";
  }
  get(name?: EnumEngine) {
    if (!name) {
      name = this.name;
    }
    return { name, title: EnginesTitle[name] };
  }
  change(name: EnumEngine) {
    const engine = this.get(name);
    if (!engine) {
      return;
    }
    this.name = name;
    cache("engine", name);
    this.statusBar.text = EnginesTitle[name];
    vscode.window.showInformationMessage(`已切换到${engine.title}引擎`);
    this.emit("change", engine);
  }
  deactivate() {
    this.statusBar.dispose();
  }
  activate() {
    if (this._active) {
      return;
    }
    this._active = true;
    this.name = (cache("engine") as EnumEngine) || EnumEngine.E_LF;
    if (!this.get(this.name)) {
      this.name = EnumEngine.E_LF;
    }
    this.statusBar.text = EnginesTitle[this.name];
    const commandSelectEngine = vscode.commands.registerCommand("mirServer.statusBar.SelectEngine", () => {
      const list = Object.keys(EnginesTitle)
        .map((name) => {
          return new EngineQuickPickItem(name as EnumEngine, this.name === name);
        })
        .sort((a) => {
          return a.name === this.name ? -1 : 1;
        });
      vscode.window.showQuickPick(list, { placeHolder: "请选择引擎" }).then((item) => {
        if (!item?.name || !EnginesTitle[item.name]) {
          return;
        }
        this.change(item.name);
      });
    });
    mirServer.context.subscriptions.push(commandSelectEngine);
  }
}

class EngineQuickPickItem implements vscode.QuickPickItem {
  label: string;
  description: string;
  picked?: boolean;
  constructor(
    public name: EnumEngine,
    picked?: boolean,
    public iconPath?: vscode.ThemeIcon
  ) {
    this.label = EnginesTitle[name];
    this.description = name;
    this.picked = picked;
  }
}
